/**  
 * Copyrights@2006, Tianyuan DIC Information Co.,Ltd.
 * 文件名:    TMallPayHandle.java  
 * 描述:   
 * 作者:     kaiyang
 * 版本:    1.0  
 * 创建时间:   2015年5月4日 上午11:57:29  
 *  
 * 修改历史:  
 * 日期                          作者           版本         描述  
 * ------------------------------------------------------------------  
 * 2015年5月4日      kaiyang      1.0        1.0 Version  
 */ 
package com.hp.bon.sgw.wh.channel.handler;

import static com.hp.bon.sgw.Constants.LOG;

import java.io.IOException;
import java.io.PrintStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang.StringEscapeUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hp.bon.sgw.Constants;
import com.hp.bon.sgw.Constants.MessageType;
import com.hp.bon.sgw.bean.SysParamBean;
import com.hp.bon.sgw.bean.XmlMessage;
import com.hp.bon.sgw.core.BuzProcessorManager;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.core.ChannelServer;
import com.hp.bon.sgw.core.channel.SoapChannel;
import com.hp.bon.sgw.core.channel.handler.IAsynCallHandler;
import com.hp.bon.sgw.domain.MessageDetail;
import com.hp.bon.sgw.domain.Node;
import com.hp.bon.sgw.service.ConfigService;
import com.hp.bon.sgw.start.SpringContext;
import com.hp.bon.sgw.threads.MessageDetailCacheManager;
import com.hp.bon.sgw.threads.TaskManager;
import com.hp.bon.sgw.wh.Constants.AliParam;
import com.hp.bon.sgw.wh.Constants.IVRParam;
import com.hp.bon.sgw.wh.bean.Recharge;
import com.hp.bon.sgw.wh.bean.TInterfacePassword;
import com.hp.bon.sgw.wh.bean.tmall.WingBalanceQuery;
import com.hp.bon.sgw.wh.channel.RenewChannel;
import com.hp.bon.sgw.wh.service.TMallResponseService;
import com.hp.bon.sgw.wh.service.TYConfigService;
import com.hp.bon.sgw.wh.service.TmallLogDao;
import com.hp.ocs.diameter.message.AVP;
import com.hp.ocs.diameter.message.AVP_Grouped;
import com.hp.ocs.diameter.message.AVP_Integer32;
import com.hp.ocs.diameter.message.AVP_UTF8String;
import com.hp.ocs.diameter.message.Message;

import freemarker.template.Template;

/**  
 * @ClassName: TMallPayHandle   
 * @Description: TODO  
 * @author: kaiyang  
 * @date:2015年5月4日 上午11:57:29     
 */
public class DetailQueryHandle  implements IAsynCallHandler{
	private static final Logger logger = LoggerFactory.getLogger(RenewChannel.class);
	private PrintStream printStream;
	private TYConfigService tyConfigService;
	private  ConfigService configService;
	private  Map<String, Object> map;
	private String 	IP;
	private String 	responseCode;
	private String 	appCode;
	private String ips;
	private String version;
	private  XmlMessage reqXmlMessage;
    private Template template1 = null;
    public static String temp="";
    public static String ip="";
    public  String password="";
    public  String url="";
    public  WingBalanceQuery wingBalanceQuery;
    public static String validMark="";
    public static String validBalances="";
    public static String queryFlags="";
    public  Map<String, Recharge> rechargeMap= new HashMap<String, Recharge>();
	public Recharge recharge= new Recharge();
	TmallLogDao tmallLogDao=(TmallLogDao)SpringContext.getInstance().getApplicationContext().getBean("tmallLogDao");
	TInterfacePassword tInterfacePassword = tmallLogDao.getTInterfacePassword();
	public DetailQueryHandle(Map<String,Object> map,ConfigService configService)
	{
		this.map = map;
		this.configService =configService;
	}
	
	@Override
	public int getProtocolType() {
		return 0;
	}
  
	@Override
	public void onCallResult(CallParam callParam) {
		logger.info("onCallResultonCallResult");
		long receiveTime = System.currentTimeMillis();
		XmlMessage ack = null;
		Object response = null;
		XmlMessage reqM = (XmlMessage) callParam.getRequest();
		if (callParam.getResponse() != null) {
			response = callParam.getResponse();
		} else if (callParam.getRecvResponse() != null) {
			response = callParam.getRecvResponse();
		}
		
		if (response == null) {
			logger.info("response == null");
			ack = SoapChannel.createERRAnwser(
					callParam.getSessionId(),
					callParam.getRetCode() == 3002 ? 11202 : callParam
							.getRetCode(), callParam.getResultMsg());
		} else {
			logger.info("response:feikong");	
			if (response instanceof Message) {// CCA -> XML
				logger.warn("CCA -> XML");	
				ack = BuzProcessorManager.getInstance().convertMessageToAck(
						callParam);
			} else if (response instanceof XmlMessage) {
				logger.info("response instanceof XmlMessage");	
				ack = (XmlMessage) response;
			} else {
				logger.info("unknown response type:"
						+ callParam.getResponse().getClass().getName());
			}
		}
		try {
			String respXML = convertResponseString((Message)response,callParam.getServiceResultCode(),callParam.getSessionId(),map);
		
			Node node = ChannelServer.routeMap.get(callParam.getServiceContextId()).curNode;
			callParam.setToNode(node);
			String url = callParam.getToNode().getServerUrl();
			PostMethod post = new PostMethod(url);
			boolean sendOK = false;
			String resp = "";
			XmlMessage ackM = new XmlMessage(true);
			try {
				
				RequestEntity requestEntity = new StringRequestEntity(respXML, "text/xml", "UTF-8");
				post.setRequestEntity(requestEntity);
				HttpClient client = new HttpClient();
				int timeout = configService.getIntValue(SysParamBean.KEY_AGREEMENT_SCSP_MSG_Timeout, 60);
				client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout*1000);
				client.executeMethod(post);
				resp = post.getResponseBodyAsString();
				sendOK = true;
			} catch (UnsupportedEncodingException e) {
				LOG.warn("unsupported encoding of request.", e);
				ackM.setRC(String.valueOf(Constants.ResultCode.TYPE_ERROR));
				ackM.setDS("unsupported encoding of request.");
			} catch (HttpException e) {
				LOG.warn("send ws request to BON error.", e);
				ackM.setRC(String.valueOf(Constants.ResultCode.BON_ERROR));
				ackM.setDS("send ws request to BON error.");
			} catch (IOException e) {
				LOG.warn("send ws request to BON time out: ", e);
				ackM.setRC(String.valueOf(Constants.ResultCode.BON_TIMEOUT));
				ackM.setDS("send ws request to BON time out: ");
			} catch (Exception e){
				LOG.warn("send ws request to BON error.", e);
				ackM.setRC(String.valueOf(Constants.ResultCode.BON_ERROR));
				ackM.setDS("send ws request to BON error.");
			}
			
			//解析返回串
			String data = "";
			if(sendOK){
				try {
					data = parseNetListReturn(resp);
				} catch (Exception e) {
					LOG.warn("response from BON is valid.", e);
					ackM.setRC(String.valueOf(Constants.ResultCode.BON_ERROR));
					ackM.setDS("response from BON is valid.");
				}
			}
			
			ackM.setDATA(data);
			ackM.setMID(reqM.getMID());
			ackM.setRTT(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(System.currentTimeMillis()));
			callParam.setResponse(ackM);
			String respXMLa = convertResponseString(ackM);
			byte[] resps = respXMLa.getBytes("UTF-8");
			ackM.setLength(resps.length);
			ackM.setMsgTime(System.currentTimeMillis());
			printStream.write(resps);
			printStream.close();

			callParam.setResponse(ack);
			
			if (callParam.getRetCode() == Constants.ResultCode.SUCCESS) {// 成功的消息，请求应答入库
				MessageDetail detail = new MessageDetail();
				detail.setBusinessCallId(callParam.getBussinessCallId());
				detail.setSessionId(callParam.getSessionId());
				detail.setServiceContextId(callParam.getServiceContextId());
				detail.setMessageType(MessageType.WSA);
				detail.setDetails(ack.getDATA());
				detail.setMsgTime(new Date(ack.getMsgTime()));
				detail.setOpType("send");
				detail.setHostId(callParam.getUserName());
				MessageDetailCacheManager.getInstance().add(detail);
			}
			TaskManager.taskProcess(callParam);
			logger.info("http response(Recharge)aa " + respXML);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	private String parseNetListReturn(String representation) throws Exception {
		StringBuffer data = new StringBuffer();
		Document doc = DocumentHelper.parseText(representation);
		Element root = doc.getRootElement();
		Element returnE = root.element("Body").element("hqueryResponse").element("return");
		returnE.setName("Service_Information");
		String xmlStr = returnE.asXML();
    	data.append(xmlStr);
		return data.toString();
	}
	private String convertResponseString(Message answer, int serviceResultCode,String sessionId,Map<String,Object> map)
	{
		
		String response = "";	    	
		Map<String,String> data = new HashMap<String, String>();
	
		 if (serviceResultCode == 0)   
		{
			try{
			    //service_infomation
			    AVP avp = answer.find(Constants.DIAMETER_AVP_SERVICE_INFOMATION,Constants.DIAMETER_VENDOR_3GPP);
			    AVP_Grouped avpServiceInfomation = new AVP_Grouped(avp);
			    //Bill_Serial_Nbr
			    AVP queryFlagAvp = avpServiceInfomation.find(5087,Constants.DIAMETER_VENDOR_CT);
			    if (queryFlagAvp != null){
			    	int  queryFlag= new AVP_Integer32(queryFlagAvp).queryValue();
			    	queryFlags=String.valueOf(queryFlag);
			    	AliParam.setQueryFlag(String.valueOf(queryFlag));
			    	data.put("queryFlag",String.valueOf(queryFlag));
			    }
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		else   //充值失败
		{
		    logger.info("设置异常1"+serviceResultCode);
			temp=String.valueOf(serviceResultCode);
		    logger.info("设置异常2"+serviceResultCode);
		
		}
		
	
		response = getResponse1(data);;
		return response;
	}
	public String getResponse1(Map<String, String> data)
	{  
		logger.info("============getResponse1=======");
	    String context = "";
	    if (template1 != null)
	    {
	      StringWriter writer = new StringWriter();
	      try {
	        template1.process(data, writer);
	      } catch (Exception e) {
	    	  logger.error("TMallResponseService getResponse error, msg = {}", e.getMessage());
	        e.printStackTrace();
	      }
	      context = writer.toString();
	    }
	    logger.info("response = {}",context);
	    return context;
	   
	}
	protected String convertResponseString(XmlMessage ack) {
		String orinData = ack.getDATA();
		String dataStr = (orinData == null || orinData.isEmpty()) ? orinData
				: "<![CDATA[" + orinData + "]]>";
		String errMsg = ack.getDS();
		errMsg = (errMsg != null) && (errMsg.indexOf('&') == -1)
				&& (errMsg.indexOf('>') == -1) && (errMsg.indexOf('<') == -1) ? errMsg
				: StringEscapeUtils.escapeXml(errMsg);
		StringBuilder respXML = new StringBuilder();
		respXML.append("<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Header/><SOAP-ENV:Body><ns3:SgwQueryAck xmlns:ns3=\"http://www.chinatelecom.cn/SGW/SOAP\"><MID>");
		respXML.append(ack.getMID());
		respXML.append("</MID><REPTAG>0</REPTAG><RTT>");
		respXML.append(ack.getRTT());
		respXML.append("</RTT><SIG>");
		respXML.append(ack.getSIG());
		respXML.append("</SIG><RC>");
		respXML.append(ack.getRC());
		respXML.append("</RC><DS>");
		respXML.append(errMsg);
		respXML.append("</DS>");
		respXML.append("<DATA>");
		respXML.append(dataStr);
		respXML.append("</DATA></ns3:SgwQueryAck></SOAP-ENV:Body></SOAP-ENV:Envelope>");
		return respXML.toString();
	}
	
}
